<template>
  <div class="radio-options">
    <el-radio-group v-model="radioGroupValue">
      <el-radio
        v-for="item in options"
        :key="item[valueField]"
        :label="item[valueField]"
      >
        <span>{{item[textField]}}</span>
      </el-radio>
    </el-radio-group>
    <span
      v-if="clearable && this.value != null"
      class="clear-button el-icon-circle-close"
      @click="onClearClick"
    ></span>
  </div>
</template>

<script>
export default {
  name: 'RadioOptions',
  model: {
    event: 'change'
  },
  props: {
    value: null,
    options: {
      type: Array
    },
    textField: {
      type: String,
      default: 'text'
    },
    valueField: {
      type: String,
      default: 'value'
    },
    clearable: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    const val = this.value;
    return {
      radioGroupValue: val == null ? null : val
    };
  },
  watch: {
    value(val) {
      this.radioGroupValue = val == null ? null : val;
    },
    radioGroupValue(newValue) {
      this.$emit('change', newValue);
    }
  },
  methods: {
    onClearClick() {
      this.radioGroupValue = undefined;
    }
  }
}
</script>

<style scoped>
.radio-options {
  display: inline-block;
}
.el-radio-group > .el-radio {
  margin-right: 8px;
}
>>> .el-radio__label {
  padding-left: 2px;
}
.clear-button {
  position: relative;
  left: 6px;
  top: 1px;
  padding: 2px;
  color: #909399;
  font-size: 15px;
  transition: 0.1s color ease-in-out;
  cursor: pointer;
}
.clear-button:hover {
  color: #303133;
  font-weight: bold;
}
</style>